<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>发票管理系统</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        input, button { margin: 5px; padding: 5px; }
        table { border-collapse: collapse; width: 100%; margin-top: 10px; }
        th, td { border: 1px solid #ccc; padding: 8px; }
        th { background-color: #f0f0f0; }
        img { max-width: 600px; display: block; margin-top: 10px; }
        #preview { max-width: 300px; display: none; margin-top: 10px; }
        pre { background: #f8f8f8; padding: 10px; }
    </style>
</head>
<body>

    <h1>发票上传识别</h1>
    <input type="file" id="fileInput" accept="image/*">
    <button onclick="uploadFile()">上传识别</button>
    <img id="preview">
    <h3>识别结果</h3>
    <pre id="uploadResult"></pre>

    <hr>

    <h1>发票查询与统计</h1>
    <label>起始日期：<input type="date" id="startDate"></label>
    <label>结束日期：<input type="date" id="endDate"></label>
    <label>关键词：<input type="text" id="keyword" placeholder="买方/卖方/代码等"></label>
    <button onclick="searchInvoices()">查询</button>

    <h2>统计结果</h2>
    <div id="summary">总数：0 张，总金额：0 元</div>

    <h2>查询结果</h2>
    <table id="resultTable">
        <thead>
            <tr>
                <th>发票ID</th>
                <th>代码</th>
                <th>日期</th>
                <th>买方</th>
                <th>卖方</th>
                <th>金额</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <div id="imageViewer"></div>

    <script>
        // 上传预览
        const fileInput = document.getElementById('fileInput');
        fileInput.onchange = () => {
            const file = fileInput.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = e => {
                    const img = document.getElementById('preview');
                    img.src = e.target.result;
                    img.style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        };

        // 上传识别
        async function uploadFile() {
            const file = fileInput.files[0];
            if (!file) {
                alert("请先选择图片！");
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            try {
                const response = await fetch('http://127.0.0.1:8000/upload_invoice/', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                document.getElementById('uploadResult').textContent = JSON.stringify(data, null, 2);
            } catch (error) {
                console.error('上传失败', error);
                alert('上传失败，请检查服务器日志');
            }
        }

        // 查询与统计
        async function searchInvoices() {
            const start = document.getElementById('startDate').value;
            const end = document.getElementById('endDate').value;
            const keyword = document.getElementById('keyword').value.trim();

            const params = new URLSearchParams();
            if (start) params.append('start_date', start);
            if (end) params.append('end_date', end);
            if (keyword) params.append('keyword', keyword);

            try {
                // 查询列表
                const res = await fetch(`http://127.0.0.1:8000/search_invoices/?${params}`);
                const data = await res.json();
                const tbody = document.querySelector("#resultTable tbody");
                tbody.innerHTML = "";
                data.forEach(item => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${item.id}</td>
                        <td>${item.invoice_code}</td>
                        <td>${item.issue_date}</td>
                        <td>${item.buyer_info.name || ""}</td>
                        <td>${item.seller_info.name || ""}</td>
                        <td>${item.total_amount}</td>
                        <td><button onclick="viewImage('${item.image_file}')">查看图片</button></td>
                    `;
                    tbody.appendChild(row);
                });

                // 查询统计
                const statRes = await fetch(`http://127.0.0.1:8000/statistics/?${params}`);
                const stat = await statRes.json();
                document.getElementById("summary").textContent = `总数：${stat.count} 张，总金额：${stat.total_amount} 元`;

                document.getElementById("imageViewer").innerHTML = "";

            } catch (error) {
                console.error("查询失败", error);
                alert("查询失败，请检查后端服务状态");
            }
        }

        // 查看图片
        function viewImage(imageFile) {
            const img = document.createElement('img');
            img.src = `http://127.0.0.1:8000/static/uploads/${imageFile}`;
            document.getElementById("imageViewer").innerHTML = "";
            document.getElementById("imageViewer").appendChild(img);
        }
    </script>

</body>
</html>
